import { Vector3 } from 'three';
import { wsApi } from '../../../../server/wsApi';
import {
  CSLineSegments,
  QueryParamKeys,
  getQueryParam,
  http,
} from '@amcax/base';
import { BaseCommand } from '@amcax/base';
import { ctx2, dataManager } from '../../../../module';

/**翼型设计表单数据类型*/
export type AirFormDataLike = {
  /**最大弯度*/
  camber_max: number;
  /**最大弯度位置*/
  camber_max_pos: number;
  /**最大厚度*/
  thickness_max: number;
  /**最大厚度位置*/
  thickness_max_pos: number;
  /**前缘半径指数*/
  leading_radius_index: number;
  /**攻角*/
  lift_angle: number;
  /**马赫数*/
  mach_number: number;
  /**雷诺数*/
  reynolds_number: number;
};

/**评估结果数据类型*/
export type Forecast = {
  /**阻力系数*/
  drag: number;
  /**升力系数*/
  lift: number;
};

/**命令参数类型*/
export type dataProps = {
  params: Array<Vector3>;
  dxid: string;
};

/**接口参数类型*/
export type CmdAirfoilProps = {
  points: Array<Vector3>;
};

/**项目id*/
const documentId = getQueryParam<string>(QueryParamKeys.DOCUMENT_ID);

/**获取翼型点列表*/
export const getAirfoilVertexes = async () => {
  const models = ctx2.cadScene.edgeGroup.children;
  const length = models.length;
  if (length === 0) {
    return null;
  }

  const airfoilID = await wsApi.getAppData(documentId + 'dxid');
  const parsedAirfoilID = JSON.parse(airfoilID);

  const vertexes = models
    .filter((item) => (item as CSLineSegments).modelDxid === parsedAirfoilID)
    .map((item) => {
      const edge = item as CSLineSegments;
      const objectInfo = dataManager.getObjectInfoByDxid(edge.modelDxid);
      const points = objectInfo.params.points;
      const vets = points.map((point) => new Vector3(point[0], point[1], 0));
      return vets;
    });

  return vertexes?.length > 0 ? vertexes[0] : null;
};

/**
 * 创建翼型线
 */
export const createAirFoilLine = async (params: Array<Vector3>) => {
  const polygon = await wsApi.fitCurve(params);
  await wsApi.saveAppData(documentId + 'dxid', JSON.stringify(polygon.id));
  return polygon.id;
};

/**
 * 更新翼型线
 */
const upadateAirFoilLine = async (dxid: string, params: Array<Vector3>) => {
  const points = [];
  for (let i = 0, l = params.length; i < l; i++) {
    const point = [params[i].x, params[i].y, params[i].z];
    points.push(point);
  }
  await wsApi.setParams(dxid, { points: points });
  ctx2.viewer.sceneSetup.fit2DView();
};

export const cmdAirfoilAPI: BaseCommand = {
  id: 'CmdAirfoilAPI',
  initialDisabled: true,
  invoke: (data: dataProps) => {
    let id = null;
    if (!data.dxid) {
      id = createAirFoilLine(data.params);
    } else {
      upadateAirFoilLine(data.dxid, data.params);
    }
    return id;
  },
};
